<template>
  <div>
    <div class="table-wrapper">
      <el-table
        ref="multipleTable"
        :row-key="rowKey"
        :lazy="lazy"
        :load="lazyFun"
        size="small"
        :data="datas"
        :[treetable]="treeProps"
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="!tree && checkboxItem" fixed="left" type="selection" min-width="55" />
        <el-table-column
          v-for="(item, index) in pageKey"
          :key="index"
          :min-width="item.args.width"
          :prop="item.key"
          :label="item.title"
        >
          <template slot-scope="scope">
            <!-- <el-row type="flex" align="middle"> -->
            <i v-if="draggable && index == 0" class="el-icon-rank" />
            <div v-if="item.type == 'custom'" class="line">
              <component :is="customComponents[item.key]" :row="scope.row" :field="item.key" />
            </div>
            <div v-else-if="item.type == 'time'" class="line">
              {{ scope.row[item.key] | formatTime }}
            </div>
            <span v-else v-text="$util.isDef(scope.row[item.key]) ? scope.row[item.key] : '-'" />
            <!--
            <el-popover
              v-else
              :open-delay="400"
              trigger="hover"
              popper-class="copy-popper"
              placement="right"
              @hide="copyText = '复制'"
            >
              <div v-if="scope.row[item.key]">
                <span
                  v-clipboard:copy="scope.row[item.key] ? scope.row[item.key] : '-'"
                  v-clipboard:success="copySuccess"
                >{{ copyText }}</span>
              </div>
              <span v-else class="disabled">复制</span>
              <span slot="reference" v-text="$util.isDef(scope.row[item.key]) ? scope.row[item.key] : '-'" />
            </el-popover>-->
            <!-- </el-row> -->
          </template>
        </el-table-column>
        <el-table-column v-if="actionWidth > 0" label="操作" :width="actionWidth" align="left" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-for="(action, index) in getDefaultActions(scope, 3)"
              :key="index"
              type="text"
              size="small"
              :disabled="!actionDisplay(action,scope)"
              @click="action.callback(scope)"
            >{{ action.title }}
            </el-button>
            <el-dropdown v-if="getMoreActions(scope).length > 1" trigger="click">
              <span class="el-dropdown-link">更多</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item
                  v-for="(action, index) in getMoreActions(scope)"
                  :key="index"
                  @click.native="action.callback(scope)"
                >{{ action.title }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button
              v-for="(action, index) in getMoreActions(scope)"
              v-else
              :key="index + 3"
              type="text"
              size="small"
              @click="action.callback(scope)"
            >
              {{ action.title }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 底部操作栏 -->
    <div v-if="(pagination || checkboxItem || !tree) && !tree" class="operation-wrapper">
      <div class="operation-placeholder" />
      <div class="operation-fixed">
        <el-row type="flex" justify="space-between">
          <div class="operation-left">
            <el-checkbox
              v-if="checkboxItem"
              v-model="allChecked"
              size="mini"
              type="text"
              @change="toggleSelection()"
            >全选
            </el-checkbox>
            <slot v-if="checkboxItem" name="table-button" :rows="multipleSelection" />
          </div>
          <div v-if="pagination && !tree" class="operation-right">
            <edu-pagination />
          </div>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Sortable from 'sortablejs'
import EduPagination from './pagination.vue'

export default {
  components: {
    EduPagination
  },
  props: {
    // 自定义组件
    customComponents: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 每条数据key值标识
    rowKey: {
      type: String,
      default: 'id'
    },
    // 操作选项配置
    doactions: {
      type: Array,
      default: (_) => {
        return []
      }
    },
    // 是否为树形结构列表
    tree: {
      type: Boolean,
      default: false
    },
    // 树形节点配置
    treeProps: {
      type: Object,
      default: () => {
        return { children: 'children', hasChildren: 'hasChildren' }
      }
    },
    // 是否使用懒加载
    lazy: {
      type: Boolean,
      default: false
    },
    // 懒加载方法
    lazyFun: {
      type: Function,
      default: _ => {
      }
    },
    // 是否显示多选
    checkboxItem: {
      type: Boolean,
      default: true
    },
    // 是否显示分页
    pagination: {
      type: Boolean,
      default: true
    },
    // 是否需要拖动
    draggable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      allChecked: false,
      multipleSelection: [],
      copyText: '复制'
    }
  },
  computed: {
    // 列表配置数据
    ...mapState('pageList/pagekey', {
      pageKey: 'pagekeyList'
    }),
    ...mapState('pageList/datas', ['datas']),
    // 获取树形结构参数
    treetable() {
      return this.tree === true ? 'tree-props' : null
    },
    rowActions() {
      return this.doactions.filter((item) => {
        return this.hasPermission(item.meta) === true
      })
    },
    // 计算操作文字总长度
    actionTextTotalLength() {
      let length = 0
      this.rowActions.slice(0, 4).forEach((item) => {
        length += item.title.length
      })

      return length
    },
    actionWidth() {
      const rowsLength = this.rowActions.length
      if (rowsLength == 0) {
        return 0
      }
      if (rowsLength > 3) {
        return 12 * this.actionTextTotalLength + 12 * 3 + 28
      } else {
        return 12 * this.actionTextTotalLength + 12 * (rowsLength - 1) + 28
      }
    }
  },
  mounted() {
    this.draggable && this.setSort()
  },
  methods: {
    actionDisplay(action, scope) {
      if (this.$util.isFunction(action.display)) {
        return action.display(scope)
      }

      return true
    },
    handleSelectionChange: function (val) {
      this.multipleSelection = val
      this.allChecked = val.length === this.datas.length
    },
    // 全选
    toggleSelection: function () {
      if (this.allChecked) {
        this.$refs.multipleTable.toggleAllSelection()
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    copySuccess: function () {
      this.copyText = '复制成功'
    },
    getDefaultActions: function (scope, length) {
      const actions = []
      this.rowActions.forEach((action) => {
        // if (actions.length < length && this.actionDisplay(action, scope)) {
        if (actions.length < length) {
          actions.push(action)
        }
      })

      return actions
    },
    getMoreActions: function (scope) {
      const actions = []
      const more = []
      this.rowActions.forEach((action) => {
        // if (actions.length >= 3 && this.actionDisplay(action, scope)) {
        if (actions.length >= 3) {
          more.push(action)
        } else {
          // if (this.actionDisplay(action, scope)) {
            actions.push(action)
          }
      })

      return more
    },
    setSort() {
      const el = this.$refs.multipleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        handle: '.el-icon-rank',
        ghostClass: 'sortable-ghost',
        chosenClass: 'sortable-chosen', // Class name for the chosen item
        dragClass: 'sortable-drag',
        setData: function (dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: (evt) => {
          const targetRow = this.datas.splice(evt.oldIndex, 1)[0]
          this.datas.splice(evt.newIndex, 0, targetRow)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.table-wrapper {
  margin: 0 30px 32px 20px;

  ::v-deep .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
    font-size: 12px;
    line-height: 1;
    margin-left: 10px;
  }

  ::v-deep .el-table {
    color: #333;
  }

  ::v-deep .el-table thead {
    color: #999;
  }

  ::v-deep thead.has-gutter th,
  ::v-deep thead th {
    background-color: #f6f9ff;
  }

  .el-icon-rank {
    font-size: 16px;
    cursor: move;
    margin-right: 5px;
  }
}

.operation-wrapper {
  .operation-placeholder {
    height: 57px;
  }

  .operation-fixed {
    padding: 10px 30px 15px 20px;
    position: fixed;
    bottom: 0;
    left: 244px;
    right: 0;
    z-index: 10;
    background-color: #fff;
    border-top: 1px solid #e4e7ed;

    .operation-left {
      ::v-deep .el-checkbox {
        margin-right: 10px;
      }
    }
  }
}

.ps__rail-x {
  display: block;
  z-index: 99; /*大于fixed table 的z-index*/
}

/* .tableX为要显示滚动条的类名 */
/* 显示横向滚动条 */
.tableX .el-table--scrollable-x .el-table__body-wrapper {
  padding: 0 0 5px 0;
  margin: 0 0 5px 0;
  overflow-x: auto;
}

/* 滚动条的滑块样式 */
.tableX .el-table .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ccc !important;
  border-radius: 30px !important;
}

/* 去除右侧固定定位阴影多出来的像素 */
.tableX .el-table__fixed-right {
  height: calc(100% - 27px) !important;
}

.line {
  display: inline-block;
}
</style>
